#!/usr/bin/perl

# Dump the current xkb letter layout as a keyd config.

use warnings;
use File::Basename;
use utf8;
use open ":std", ":encoding(UTF-8)";

# Build a map of X keysyms to unicode chars
open FH, "/usr/include/xkbcommon/xkbcommon-keysyms.h";
while (<FH>) {
	$symmap{$1} = chr(hex($2)) if (/XKB_KEY_([^  \t]*)\s.*U\+([0-9a-fA-F]*)/);
}

# Map X keycodes to their corresponding keyd names
%codemap = (
	24 => "q",
	25 => "w",
	26 => "e",
	27 => "r",
	28 => "t",
	29 => "y",
	30 => "u",
	31 => "i",
	32 => "o",
	33 => "p",
	34 => "[",
	35 => "]",
	38 => "a",
	39 => "s",
	40 => "d",
	41 => "f",
	42 => "g",
	43 => "h",
	44 => "j",
	45 => "k",
	46 => "l",
	47 => ";",
	48 => "'",
	52 => "z",
	53 => "x",
	54 => "c",
	55 => "v",
	56 => "b",
	57 => "n",
	58 => "m",
	59 => ",",
	60 => ".",
	61 => "/",
	10 => "1",
	11 => "2",
	12 => "3",
	13 => "4",
	14 => "5",
	15 => "6",
	16 => "7",
	17 => "8",
	18 => "9",
	19 => "0",
	51 => "\\",
	20 => "-",
	21 => "=",
);

sub sym_to_char {
	$sym = $_[0];
	return "" if (!$sym);

	if ($sym =~ /U([0-9A-Fa-f]+)/) {
		 return chr(hex($1));
	} elsif ($symmap{$sym}) {
		 $symmap{$sym};
	} else {
		print STDERR "Could not resolve sym: $sym\n";
		return "";
	}
}

for (`xmodmap -pke`) {
	if (/keycode\s*([0-9]+)\s*=\s*(.*)/ && $codemap{$1}) {
		$key = $codemap{$1};
		@syms=split " ", $2;

		$keymap{$key} = $sym if ($sym = sym_to_char $syms[0]);
		$shifted_keymap{$key} = $sym if ($sym = sym_to_char $syms[1]);
		$altgr_keymap{$key} = $sym if ($sym = sym_to_char $syms[4]);
		$shifted_altgr_keymap{$key} = $sym if ($sym = sym_to_char $syms[5]);
	}
}

`setxkbmap -query` =~ /layout:\s*(\S*)/;
$shift_layer = "$1_shift";

print "[$1:layout]\n\n";
print "$_ = $keymap{$_}\n" foreach (sort keys %keymap);
print "shift = layer(${1}_shift)\n";
print "altgr = layer(${1}_altgr)\n" if (%altgr_keymap);
print "\n";

print "[${1}_shift:S]\n";
print "$_ = $shifted_keymap{$_}\n" foreach (sort keys %shifted_keymap);

if (%altgr_keymap) {
	print "\n";
	print "[${1}_altgr:G]\n";
	print "$_ = $altgr_keymap{$_}\n" foreach (sort keys %altgr_keymap);
	print "\n";

	print "[${1}_altgr+${1}_shift]\n";
	print "$_ = $shifted_altgr_keymap{$_}\n" foreach (sort keys %shifted_altgr_keymap);
}
